package patrol.mobile.com.mobilepatrol.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import io.rong.calllib.RongCallClient;
import io.rong.calllib.RongCallCommon;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import patrol.mobile.com.mobilepatrol.DBHelper;
import patrol.mobile.com.mobilepatrol.LocationHelper;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.bean.MyUserBean;
import patrol.mobile.com.mobilepatrol.fragment.MessageFragment;
import patrol.mobile.com.mobilepatrol.fragment.NewMainFragment;
import patrol.mobile.com.mobilepatrol.fragment.SelfFragment;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;
import patrol.mobile.com.mobilepatrol.widget.BottomTabView;


/**
 * Created by shj
 * 主activity
 */

public class MainActivity extends BottomTabBaseActivity implements AMapLocationListener {
    private static MainActivity instance;
    private long mExitTime = 0;
    private DBHelper dbHelper;
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    public static double lat;
    public static double lon;
    private int WRITE_COARSE_LOCATION_REQUEST_CODE = 1001;

// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbHelper = new DBHelper(this);
//        showToast(dbHelper.getTaskDataInfo().size()+"");
        instance = this;
        linkRongYun();
        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(10000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    WRITE_COARSE_LOCATION_REQUEST_CODE);//自定义的code
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //可在此继续其他操作。
        mlocationClient.startLocation();
    }

    @Override
    protected List<BottomTabView.TabItemView> getTabViews() {
        List<BottomTabView.TabItemView> tabItemViews = new ArrayList<>();
        tabItemViews.add(new BottomTabView.TabItemView(this, "消息", R.color.bf,
                R.color.colorPrimary, R.mipmap.message_gray, R.mipmap.message_red));
        /*tabItemViews.add(new BottomTabView.TabItemView(this, "首页", R.color.bf,
                R.color.colorPrimary, R.mipmap.first_gray, R.mipmap.first));*/
        tabItemViews.add(new BottomTabView.TabItemView(this, "首页", R.color.bf,
                R.color.colorPrimary, R.mipmap.first_gray, R.mipmap.first));
        tabItemViews.add(new BottomTabView.TabItemView(this, "我的", R.color.bf,
                R.color.colorPrimary, R.mipmap.my_gray, R.mipmap.my));
//        tabItemViews.add(new BottomTabView.TabItemView(this, "初始化", R.color.bf,
//                R.color.colorPrimary, R.mipmap.bridge_patrol_gray, R.mipmap.bridge_patrol));
        return tabItemViews;
    }

    @Override
    protected List<Fragment> getFragments() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(MessageFragment.newInstance("", ""));
//        fragments.add(new MainFragment());
        fragments.add(NewMainFragment.newInstance("", ""));
        fragments.add(new SelfFragment());
//        fragments.add(new InitFragment());
        return fragments;
    }

    public static void finishSelf() {
        instance.finish();
    }

    @Override
    public void onBackPressed() {
        _exit();
    }

    /**
     * 退出
     */
    private void _exit() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    /**
     * 链接融云服务器
     */
    private void linkRongYun() {
        String userData = (String) SPUtils.get(SPUtils.USER_DATA, "");
        if (TextUtils.isEmpty(userData)) {
            ToastUtils.showToast("用户信息获取失败");
            return;
        }
        MyUserBean myUserBean = new Gson().fromJson(userData, MyUserBean.class);
        String rongToken = "";
        for (MyUserBean.YhListBean yhListBean : myUserBean.getYhList()) {
            if (yhListBean.getRyid().equals(UserManager.getUserId())) {
                rongToken = yhListBean.getRongToken();
                break;
            }
        }
        if (TextUtils.isEmpty(rongToken)) {
            ToastUtils.showToast("rongToken 获取失败");
            return;
        }
        RongIM.connect(rongToken, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Log.e("RongIM", "Token错误");
                ToastUtils.showToast("Token错误");
//                startActivity(LoginActivity.class);
            }

            @Override
            public void onSuccess(String userid) {
                RongCallClient.getInstance().setVideoProfile(RongCallCommon.CallVideoProfile.valueOf(20));
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Log.e("RongIM", "连接融云失败");
                ToastUtils.showToast("连接融云失败");
//                startActivity(LoginActivity.class);
            }
        });
    }

    //启动定位
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                lat = amapLocation.getLatitude();//获取纬度
                lon = amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                Log.e("location", lat + "" + lon);
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

}
